package worker;


import java.util.ArrayList;
import java.util.Date;

import java.util.List;
import java.util.Random;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import server.AgeDomain;
import server.AlexaUpdate;
import server.GetPage;
import server.GetTrackIp;
import server.GooglePageRank;
import server.Monitor;
import server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

public class Worker implements ServletContextListener, MessageListener,
		ExceptionListener {

	private static ActiveMQConnectionFactory connectionFactory;
	private Connection connection;
	private Session session;
	private Destination destination;
	private boolean transacted = false;
	public static List<String> listSock = new ArrayList<String>();
	public static int next = 0;

	public static ArrayList<Worker> listWorker = new ArrayList<Worker>();

	public Worker() {
		listSock.add("184.107.59.40");
		listSock.add("184.107.59.41");
		listSock.add("184.107.59.42");
		listSock.add("184.107.59.43");
		listSock.add("184.107.59.44");
		listSock.add("184.107.59.45");
		listSock.add("184.107.59.46");
		listSock.add("184.107.59.47");

		try {
			setUp();
			try {
				createConsumerAndReceiveAMessage();

				// thuan loi
				if (!listWorker.contains(this)) {
					listWorker.add(this);

				}

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setUp() throws JMSException {

		connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD,
				"failover:tcp://y1s.org:61616");
		connection = connectionFactory.createConnection();
		connection.start();
		session = connection
				.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
		destination = session.createQueue("domain");
	}

	private void createConsumerAndReceiveAMessage() throws JMSException,
			InterruptedException {

		MessageConsumer consumer = session.createConsumer(destination);

		connection.setExceptionListener(this);
		consumer.setMessageListener(this);
	}

	public void cleanUp() {
		try {
			this.connection.close();
			listWorker.remove(this);

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void getSocks() {
		next++;
		if(next >= 8)
		{
			next = 0;
		}
	}

	public void onMessage(Message message) {
		if (message instanceof TextMessage) {
			TextMessage textMessage = (TextMessage) message;
			
			try {
				System.out
						.println("Received message: " + textMessage.getText());

				getSocks();
				
				String name = textMessage.getText().toLowerCase()
						.replaceAll("(http|https)+://(www.)*", "")
						.replaceAll("^[\\w\\W]+[\\/]{2}", "")
						.replaceAll("[\\/]+[\\w\\W]+$", "")
						.replaceAll("www.", "");

				DBCollection coll = Data.data("domain");

				DBObject domain = coll.findOne(new BasicDBObject("name", name));

				System.out.println(domain);

				if (domain == null) {

					Thread[] group = new Thread[6];
					Random generator = new Random();
					int r = generator.nextInt(100000);
					BasicDBObject add = new BasicDBObject();
					add.put("name", name);
					add.put("update", new Date().getTime());
					add.put("random", r);
					coll.insert(add);
					DBObject domains = coll.findOne(new BasicDBObject("name",
							name));
					try {
						group[0] = new GetPage(domains);
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						group[1] = new GooglePageRank(domains);
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						group[2] = new AgeDomain(domains);
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						group[3] = new AlexaUpdate(domains,listSock.get(next));
					} catch (Exception e) {
						// TODO: handle exception
					}
					try {
						group[4] = new Whois(domains);
					} catch (Exception e) {
						// TODO: handle exception
					}
//					try {
//						group[5] = new GetTrackIp(domains);
//					} catch (Exception e) {
//						// TODO: handle exception
//					}
					new Monitor(25000, group, domains);
				}

			} catch (JMSException ex) {
				System.out.println("Error reading message: " + ex);
			}
		} else {
			System.out.println("Received: " + message);
		}
	}

	synchronized public void onException(JMSException ex) {
		this.cleanUp();

	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

		for (Worker worker : listWorker) {
			worker.cleanUp();

		}

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {

	}

	public static void main(String[] args) {
		new Worker();
	}
}
